<template>
  <div>
    <avue-crud
      :data="data"
      :table-loading="isLoading"
      :before-open="handleBeforeOpen"
      :option="option"
      @on-load="onLoad"
      @refresh-change="handleRefresh"
      v-model="form"
      @search-change="handleSearch"
      @search-reset="handleSearch({}, () => {})"
    >
      <template #status="{ row }">
        <el-tag v-if="+row.status === 1">正常</el-tag>
        <el-tag v-else type="danger">停用</el-tag>
      </template>

      <template #menu="{ row }">
        <el-popconfirm title="确定删除数据?" :hide-after="0" @confirm="handleDelete(row)">
          <template #reference>
            <el-button type="primary" text icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </avue-crud>
    <ListForm ref="listFormRef" @done="handleRefresh" />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import ListForm from "./component/ListForm.vue";
import useTableOption from "./combination/useTableOption";
import { getTreeListApi, deleteApi } from "@/api/system/dept";

const isLoading = ref(false);
const listFormRef = ref<InstanceType<typeof ListForm>>();
const data = ref([]);
const option = useTableOption();
const form = ref<any>({});
const query = ref({});

function handleSearch(params: any, done: () => void) {
  query.value = params;
  onLoad();
  done();
}

async function onLoad() {
  isLoading.value = true;
  const resp = await getTreeListApi({
    ...query.value,
  });
  data.value = resp.data;
  isLoading.value = false;
}

function handleRefresh() {
  onLoad();
}

async function handleDelete(row: any) {
  await deleteApi(row.id);
  ElMessage.success("操作成功");
  handleRefresh();
}

function handleBeforeOpen(_done: any, type: string) {
  const params: any = {
    type,
  };
  if (["edit", "view"].includes(type)) {
    params.id = form.value.id;
  }

  if (type === "view") {
    params.detail = true;
  }

  listFormRef.value?.init(params);
}
</script>
